package com.fjc.controller;

import com.fjc.domain.Student;
import com.fjc.service.StudentService;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by fjc on 2018/5/22.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private StudentService studentService;


    @RequestMapping("/login")
    public String login(String username,String password){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(usernamePasswordToken);
            SecurityUtils.getSubject().getSession().setTimeout(1800000);
            return "user";
        }catch (Exception e){
            return "login";
        }
    }


    @RequestMapping("/re")
    @ResponseBody
    public String red(){
        return studentService.shiro();
    }


    @RequestMapping("/up")
    /**
     * 变量名称要和页面上的name对上
     */
    public String up(MultipartFile[] file, HttpServletRequest request) throws IOException {
        for (MultipartFile file1:file) {
            String name = file1.getOriginalFilename();
            File newFile = new File("/" + name);
            file1.transferTo(newFile);
        }
        return "user";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> down() throws IOException {
        String path = "G:/cc.txt";
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",path);
        headers.setContentType(MediaType.TEXT_EVENT_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
}
